package csc.fresher.service;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import csc.fresher.dao.InternetAccountDAO;
import csc.fresher.entity.InternetAccount;



@Service
public class InternetLoginServiceImpl implements InternetLoginService, Serializable {
	
	public InternetLoginServiceImpl() {
		super();
	}



	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Autowired
	private InternetAccountDAO internetAccountDAO;
	private String previousLoginName=null;
	private int loginFailedCount = 0 ;
	
	private void lockAccount(InternetAccount user) {
		user.setLock(true);
		internetAccountDAO.updateInternetAccount(user);

	}



	@Override
	public InternetAccount checkLogin(String username, String password) {
		InternetAccount user = internetAccountDAO
				.getInternetAccountByUsername(username);
		if (user != null) {
			if (password.equals(user.getPassword())) {
				return user;
			} else {
				if (user.getUsername().equals(previousLoginName)) {
					loginFailedCount++;
				} else {
					previousLoginName = user.getUsername();
					loginFailedCount=1;
				}
				if (loginFailedCount>=3) {
					lockAccount(user);
				}
			}
		}
		return null;
	}

	@Override
	public boolean checkLock(String username) {
		InternetAccount account = internetAccountDAO.getInternetAccountByUsername(username);
		if (account != null) {
			if (account.isLock()) {
				return true;
			}
		}
		
		return false;
	}
	
	public void setInternetAccountDAO(InternetAccountDAO internetAccountDAO) {
		this.internetAccountDAO = internetAccountDAO;
	}




	@Override
	public boolean changePassword(InternetAccount account, String oldPassword, String newPassword) {
		// TODO Auto-generated method stub
		//InternetAccount account = (InternetAccount)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("username");
		if(oldPassword.equals(account.getPassword())){
			account.setPassword(newPassword);
			internetAccountDAO.updateInternetAccount(account);
			return true;
		}
		return false;
	}

}
